import React, { Component } from 'react'
import { connect } from 'dva';
import { Form, Input, Button, notification, InputNumber, Modal } from 'antd';
import { FormComponentProps } from "antd/lib/form/Form";

import { SearchCol, SearchRow } from '@/styled/form';
import { DropDownSelect } from '@/components/DropDownSelect/index';

import { inject_unount } from '@/utils/middleware';
import { dealElement } from '@/utils/util';

import TextArea from 'antd/lib/input/TextArea';
import { DICT } from '../enum';
import Imgviewer from '@/components/ImgViewer';


interface IProps extends FormComponentProps {
  dispatch?: Function,
  history?: any,
  dict?: any,
  data?: {
    id: string,
    buildId: string,
    floorPlan: string
  },
  location?: any,
  img?: {
    url: string,
    message: string
  },
  buttons?: Array<any>,
}

@connect(({ build_floor, upload, routing }) => ({
  dict: build_floor.dict,
  img: upload.imgValue,
  location: routing.location
}))
@inject_unount
class FormItem extends Component<IProps, any> {
  state = {
    confirmDirty: false,
    autoCompleteResult: [],
    isNew: true,
  };

  componentDidMount() {
    const { data, form, dispatch } = this.props;

    dispatch({ type: 'build_floor/init', payload: {
      dict: { keyList: DICT },
      url: data ? data.floorPlan : null
    } })

    if (data) {
      const { id, buildId, floorPlan, ...items } = data;
      form.setFieldsValue(items)
    }
  }

  handleSubmit = (e) => {
    e.preventDefault();

    const { form, data, dispatch, img, location } = this.props;

    const buildId = location.pathname.split('/')[3]
    form.validateFields((err, values) => {
      if (!err) {

        const ans = dealElement({
          floorPlan: img.url,
          buildId,
          ...values
        })

        data && data.id ? dispatch({
          type: 'build_floor/update',
          payload: {
            id: data.id,
            ...ans
          }
        }) : dispatch({
          type: 'build_floor/create',
          payload: ans
        })
      } else {
        notification['error']({
          message: `${data.id ? '修改' : '创建'}失败`,
          description: '字段验证不通过',
        });
      }
    })
  }

  uploadImage(e) {
    e.persist();
    const { dispatch } = this.props;

    const file = e.target.files[0];
    dispatch({ type: 'upload/uploadImg',  payload: file });
  }

  render() {
    const { form, data, dict = {}, img } = this.props;

    const { getFieldDecorator } = form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 12 },
        sm: { span: 8 },
      },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 12,
          offset: 0,
        },
        sm: {
          span: 8,
          offset: 4,
        },
      },
    };
    return (
      <Form onSubmit={this.handleSubmit}>
        <SearchRow>
          <SearchCol span={12}>
            <Form.Item
              {...formItemLayout}
              label='楼层名称'
            >
              {getFieldDecorator('floorName', {
                rules: [{ required: true, message: '请输入楼层名称' }],
              })(
                <Input style={{width: '100%'}} placeholder='请输入楼层名词' />
              )}
            </Form.Item>
          </SearchCol>
          <SearchCol span={12}>
            <Form.Item
              {...formItemLayout}
              label='楼层类型'
            >
              {getFieldDecorator('floorType', {
                rules: [{ required: true, message: '请选择楼层类型' }],
              })(
                DropDownSelect(dict, 'floor.type')
              )}
            </Form.Item>
          </SearchCol>
          <SearchCol span={12}>
            <Form.Item
              {...formItemLayout}
              label='楼层号'
            >
              {getFieldDecorator('floor', {
                rules: [{ required: true, message: '请输入号' }],
              })(
                <InputNumber style={{width: '100%'}} placeholder='请输入楼层名称' />
              )}
            </Form.Item>
          </SearchCol>
          <SearchCol span={12}>
            <Form.Item
              {...formItemLayout}
              label='平面图'
            >
              <input type="file" style={{opacity: 0, width: 120, zIndex: 10, position: 'absolute', cursor: 'pointer'}} onChange={(e) => {this.uploadImage(e)}} accept="image/*" />
              <Button style={{marginTop: -50}}>上传平面图</Button>
              <span>
                <Imgviewer hasText="查看平面图" missText="暂无平面图" url={img.url}/>
                { img.message === 'success' ? '上传成功' : (img.message === 'fail' ? '上传失败' : '') }
              </span>
            </Form.Item>
          </SearchCol>

        </SearchRow>
        <SearchRow>
        <SearchCol span={12}>

          <Form.Item
            {...formItemLayout}
            label='备注'
          >
            {getFieldDecorator('remark', {
              rules: [{ required: false, message: '请输入备注' }],
            })(
              <TextArea style={{width: '100%', height: '200px'}} placeholder='请输入备注' />
            )}
          </Form.Item>
        </SearchCol>
          <SearchCol span={12}>

          </SearchCol>
        </SearchRow>
        <Form.Item {...tailFormItemLayout}>
          <Button type="primary" htmlType="submit">{ !!data ? '修改' : '新建' }</Button>
          <Button style={{ marginLeft: '5%' }} onClick={() => window.history.back()}>返回列表</Button>
        </Form.Item>
      </Form>
    );
  }
}

const FormList = Form.create()(FormItem);
export default FormList;
